<template>
    <div class="program-list-container">
        <div class="action-bar">
            <div class="action-left">
                <el-button type="primary" icon="el-icon-plus" @click="handleAddProgram">添加节目</el-button>
                <el-select v-model="selectedShowId" placeholder="选择演出" clearable @change="handleShowChange" style="width: 200px; margin-left: 15px;">
                    <el-option
                        v-for="show in showList"
                        :key="show.showId"
                        :label="show.showName"
                        :value="show.showId">
                    </el-option>
                </el-select>
            </div>
            <el-input v-model="searchQuery" placeholder="搜索节目名称" prefix-icon="el-icon-search" clearable
                class="search-input" @clear="handleSearch" @keyup.enter.native="handleSearch">
                <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
            </el-input>
        </div>

        <el-card shadow="hover" class="table-card" v-if="selectedShowId">
            <div class="table-toolbar">
                <el-tooltip :content="selectedShowId ? '重新排序当前演出的节目' : '重新排序所有节目'" placement="top">
                    <el-button type="success" size="small" icon="el-icon-sort" @click="reorderPrograms" :disabled="programList.length <= 1">自动排序</el-button>
                </el-tooltip>
                <span class="info-text"><i class="el-icon-info"></i> 提示：您可以通过操作栏的上移/下移按钮调整节目顺序</span>
            </div>
            <el-table :data="programList" border stripe style="width: 100%" v-loading="loading" :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#606266' }">
                <el-table-column prop="programId" label="节目ID" width="180" align="center"></el-table-column>
                <el-table-column v-if="!selectedShowId" prop="showName" label="演出名称" width="180" align="center"></el-table-column>
                <!-- <el-table-column prop="orderNo" label="节目顺序" width="100" align="center">
                    <template slot-scope="scope">
                        <el-tag type="info">{{ scope.row.orderNo }}</el-tag>
                    </template>
                </el-table-column> -->
                <el-table-column prop="programName" label="节目名称" width="180" align="center"></el-table-column>
                <el-table-column prop="performers" label="表演者" width="150" align="center">
                    <template slot-scope="scope">
                        <div class="performers-tags">
                            <el-tooltip v-if="scope.row.performers && scope.row.performers.split(',').length > 2" :content="scope.row.performers" placement="top">
                                <div>
                                    <template v-for="(performer, index) in scope.row.performers.split(',')">
                                        <el-tag v-if="index < 2" :key="index" size="mini" type="info" class="performer-tag">
                                            {{ performer }}
                                        </el-tag>
                                    </template>
                                    <el-tag size="mini" type="info" v-if="scope.row.performers.split(',').length > 2">+{{ scope.row.performers.split(',').length - 2 }}</el-tag>
                                </div>
                            </el-tooltip>
                            <template v-else>
                                <el-tag v-for="(performer, index) in scope.row.performers ? scope.row.performers.split(',') : []" :key="index" size="mini" type="info" class="performer-tag">
                                    {{ performer }}
                                </el-tag>
                            </template>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="programTypeId" label="节目类型" width="120" align="center">
                    <template slot-scope="scope">
                        <div class="type-tags">
                            <el-tooltip v-if="scope.row.programTypeId && scope.row.programTypeId.split(',').length > 2" :content="getTypeNames(scope.row.programTypeId)" placement="top">
                                <div>
                                    <template v-for="(typeId, index) in scope.row.programTypeId.split(',')">
                                        <el-tag v-if="index < 2" :key="index" size="mini" type="success" class="type-tag">
                                            {{ getProgramTypeName(typeId) }}
                                        </el-tag>
                                    </template>
                                    <el-tag size="mini" type="success" v-if="scope.row.programTypeId.split(',').length > 2">+{{ scope.row.programTypeId.split(',').length - 2 }}</el-tag>
                                </div>
                            </el-tooltip>
                            <template v-else>
                                <el-tag v-for="(typeId, index) in scope.row.programTypeId ? scope.row.programTypeId.split(',') : []" :key="index" size="mini" type="success" class="type-tag">
                                    {{ getProgramTypeName(typeId) }}
                                </el-tag>
                            </template>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="简介" width="200" align="center">
                    <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" :content="scope.row.description" placement="top" :style="{ maxWidth: '150px', whiteSpace: 'normal', overflow: 'auto' }">
                            <span>{{ scope.row.description.length > 20 ? scope.row.description.substring(0, 20) + '...' : scope.row.description }}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="programUrl" label="图片" width="100" align="center">
                    <template slot-scope="scope">
                        <el-image 
                            style="width: 50px; height: 50px" 
                            :src="scope.row.programUrl" 
                            :preview-src-list="[scope.row.programUrl]"
                            fit="cover">
                        </el-image>
                    </template>
                </el-table-column> -->
                <el-table-column prop="createTime" label="创建时间" width="200" align="center"></el-table-column>
                <el-table-column prop="createUser" label="创建人" width="200" align="center"></el-table-column>
                <el-table-column label="操作" width="200" align="center">
                    <template slot-scope="scope">
                        <el-button-group>
                            <el-tooltip content="上移" placement="top" :disabled="scope.$index === 0">
                                <el-button type="info" size="mini" icon="el-icon-top" :disabled="scope.$index === 0" @click="moveProgram(scope.row, scope.$index, 'up')"></el-button>
                            </el-tooltip>
                            <el-tooltip content="下移" placement="top" :disabled="scope.$index === programList.length - 1">
                                <el-button type="info" size="mini" icon="el-icon-bottom" :disabled="scope.$index === programList.length - 1" @click="moveProgram(scope.row, scope.$index, 'down')"></el-button>
                            </el-tooltip>
                            <el-tooltip content="编辑" placement="top">
                                <el-button type="primary" size="mini" icon="el-icon-edit" @click="editProgram(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteProgram(scope.row)"></el-button>
                            </el-tooltip>
                        </el-button-group>
                    </template>
                </el-table-column>
                <template slot="empty">
                    <div class="empty-data">
                        <i class="el-icon-document"></i>
                        <p>暂无数据</p>
                    </div>
                </template>
            </el-table>
        </el-card>
        
        <el-card v-else shadow="hover" class="empty-show-card">
            <div class="empty-show-message">
                <i class="el-icon-tickets"></i>
                <p>请先选择一个演出以管理其节目</p>
            </div>
        </el-card>

        <el-dialog title="添加/编辑节目" :visible.sync="dialogVisible" width="500px" center>
            <el-form :model="programForm" label-width="100px" :rules="rules" ref="programForm">
                <el-form-item label="节目名称" prop="programName">
                    <el-input v-model="programForm.programName" placeholder="请输入节目名称"></el-input>
                </el-form-item>
                <el-form-item label="表演者" prop="performers">
                    <div class="performer-input">
                        <el-tag
                            :key="index"
                            v-for="(performer, index) in performerTags"
                            closable
                            :disable-transitions="false"
                            @close="handleRemovePerformer(performer)">
                            {{performer}}
                        </el-tag>
                        <el-input
                            class="input-new-performer"
                            v-if="inputPerformerVisible"
                            v-model="inputPerformerValue"
                            ref="savePerformerInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm"
                            @blur="handleInputConfirm">
                        </el-input>
                        <el-button v-else class="button-new-performer" size="small" @click="showInput">+ 添加表演者</el-button>
                    </div>
                    <div class="form-tip">
                        <i class="el-icon-info"></i>
                        <span>可添加多个表演者</span>
                    </div>
                </el-form-item>

                <el-form-item label="节目类型" prop="programTypeId">
                    <el-select 
                        v-model="programForm.programTypeId" 
                        placeholder="请选择节目类别" 
                        multiple 
                        collapse-tags
                        style="width: 100%">
                        <el-option 
                            v-for="item in programTypeList" 
                            :key="item.programTypeId" 
                            :label="item.programTypeName" 
                            :value="item.programTypeId">
                        </el-option>
                    </el-select>
                    <div class="form-tip">
                        <i class="el-icon-info"></i>
                        <span>可选择多个节目类型</span>
                    </div>
                </el-form-item>
                <el-form-item label="节目顺序" prop="orderNo">
                    <el-input-number v-model="programForm.orderNo" :min="1" :step="10" placeholder="请输入节目顺序" controls-position="right"></el-input-number>
                    <div class="form-tip">
                        <i class="el-icon-info"></i>
                        <span>建议使用10的倍数，便于后续插入新节目</span>
                    </div>
                </el-form-item>
                <el-form-item label="简介" prop="description">
                    <el-input type="textarea" v-model="programForm.description" rows="3" placeholder="请输入简介"></el-input>
                </el-form-item>
                <el-form-item label="节目图片" prop="programUrl">
                    <el-upload class="program-uploader" action="http://localhost:9002/api/system/image/imageprogram"
                        :show-file-list="false" :on-success="handleImageSuccess" :before-upload="beforeImageUpload">
                        <img v-if="programForm.programUrl" :src="programForm.programUrl" class="program-image">
                        <i v-else class="el-icon-plus program-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleCancel">取 消</el-button>
                <el-button type="primary" @click="submitProgram">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import service from '@/utils/request';

export default {
    name: 'ProgramList',
    data() {
        return {
            pagination: {
                currentPage: 1,
                pageSize: 10,
                total: 0
            },
            programList: [],
            loading: false,
            searchQuery: '',
            dialogVisible: false,
            programForm: {
                programId: '',
                programTypeId: [],
                programName: '',
                performers: '',
                description: '',
                orderNo: 10,
                programUrl: '',
                createTime: '',
                createUser: '',
                token: localStorage.getItem('token'),
                showName: '',
                showId: '',
                selectedShowId: '',
            },
            isEditMode: false,
            currentProgramId: null,
            programTypeList: [],
            performerTags: [],
            inputPerformerVisible: false,
            inputPerformerValue: '',
            rules: {
                programName: [
                    { required: true, message: '请输入节目名称', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
                ],
                programTypeId: [
                    { required: true, message: '请选择至少一个节目类型', trigger: 'change' },
                    { type: 'array', message: '请选择节目类型', trigger: 'change' }
                ],
                orderNo: [
                    { required: true, message: '请输入节目顺序', trigger: 'blur' }
                ],
                description: [
                    { required: true, message: '请输入节目简介', trigger: 'blur' }
                ],
                performers: [
                    { required: true, message: '请输入表演者', trigger: 'blur' }
                ]
            },
            showList: [],
            selectedShowId: '',
        };
    },
    created() {
        // this.fetchProgramList();
        this.fetchProgramTypes();
        this.fetchShowList();
    },
    methods: {
        fetchProgramList() {
            if (!this.selectedShowId) {
                this.programList = [];
                return;
            }
            
            this.loading = true;
            service.get('/api/content/program/getProgramList', {
                params: {
                    pageNum: this.pagination.currentPage,
                    pageSize: this.pagination.pageSize,
                    programName: this.searchQuery,
                    selectedShowId: this.selectedShowId
                }
            }).then(res => {
                if (res.code === 200) {
                    // 按节目顺序排序
                    this.programList = res.data.list.sort((a, b) => a.orderNo - b.orderNo);
                } else {
                    this.$message.error('获取节目列表失败');
                }
            }).catch(err => {
                this.$message.error(err.message);
            }).finally(() => {
                this.loading = false;
            });
        },
        fetchProgramTypes() {
            service.get('/api/content/program/getProgramTypes').then(res => {
                if (res.code === 200) {
                    this.programTypeList = res.data;
                } else {
                    this.$message.error('获取节目类型失败');
                }
            }).catch(err => {
                this.$message.error(err.message);
            });
        },
        fetchShowList() {
            service.get('/api/content/show/getShows')
                .then(res => {
                    if (res.code === 200) {
                        this.showList = res.data;
                    } else {
                        this.$message.error('获取演出列表失败');
                    }
                })
                .catch(err => {
                    this.$message.error(err.message);
                });
        },
        handleSearch() {
            this.fetchProgramList();
        },
        handleAddProgram() {
            // 验证是否选择了演出
            if (!this.selectedShowId) {
                this.$message.warning('请先选择一个演出');
                return;
            }
            
            this.isEditMode = false;
            let maxOrderNo = 0;
            
            // 查找当前演出下节目的最大顺序号
            // 在当前列表中直接找最大的顺序号，因为fetchProgramList已经按演出筛选过了
            if (this.programList.length > 0) {
                maxOrderNo = Math.max(...this.programList.map(p => Number(p.orderNo) || 0));
            }
            
            this.programForm = { 
                programId: '', 
                programTypeId: [],
                programName: '', 
                performers: '', 
                description: '', 
                orderNo: maxOrderNo + 10,
                programUrl: '',
                token: localStorage.getItem('token'),
                showId: this.selectedShowId,
                selectedShowId: this.selectedShowId,
            };
            this.performerTags = [];
            this.dialogVisible = true;
        },
        editProgram(program) {
            this.isEditMode = true;
            this.currentProgramId = program.programId;
            
            const programTypeIdArray = program.programTypeId ? program.programTypeId.split(',') : [];
            
            this.programForm = { 
                ...program, 
                programTypeId: programTypeIdArray,
                token: localStorage.getItem('token'),
                selectedShowId: program.showId,
            };
            
            this.performerTags = this.programForm.performers ? this.programForm.performers.split(',').filter(p => p.trim() !== '') : [];
            this.dialogVisible = true;
        },
        submitProgram() {
            this.programForm.performers = this.performerTags.join(',');
            
            let formToSubmit = { ...this.programForm };
            if (Array.isArray(formToSubmit.programTypeId)) {
                formToSubmit.programTypeId = formToSubmit.programTypeId.join(',');
            }
            
            this.$refs['programForm'].validate((valid) => {
                if (valid) {
                    const request = this.isEditMode
                        ? service.put('/api/content/program/updateProgram', formToSubmit)
                        : service.post('/api/content/program/addProgram', formToSubmit);

                    request.then(res => {
                        if (res.code === 200) {
                            this.$message.success(this.isEditMode ? '更新成功' : '添加成功');
                            this.dialogVisible = false;
                            this.fetchProgramList();
                        } else {
                            this.$message.error(this.isEditMode ? '更新失败' : '添加失败');
                        }
                    }).catch(err => {
                        this.$message.error(err.message);
                    });
                }
            });
        },
        deleteProgram(program) {
            this.$confirm('确认删除该节目?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                service.delete(`/api/content/program/deleteProgram/${program.programId}`).then(res => {
                    if (res.code === 200) {
                        this.$message.success('删除成功');
                        this.fetchProgramList();
                    } else {
                        this.$message.error('删除失败');
                    }
                }).catch(err => {
                    this.$message.error(err.message);
                });
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },
        // 处理图片上传成功
        handleImageSuccess(res, file) {
            if (res.code === 200) {
                this.programForm.programUrl = res.data;
                console.log('上传的文件名:', file.name);
            } else {
                this.$message.error('上传失败');
            }
        },
        // 图片上传前的验证
        beforeImageUpload(file) {
            const isImage = file.type.startsWith('image/');
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isImage) {
                this.$message.error('上传的文件必须是图片!');
            }
            if (!isLt2M) {
                this.$message.error('上传的图片大小不能超过 2MB!');
            }

            return isImage && isLt2M;
        },
        // 处理取消操作
        handleCancel() {
            // 添加逻辑以删除已上传的图片
            if (this.programForm.programUrl && !this.isEditMode) {
                service.delete('/api/system/image/deleteImageprogram', {
                    params: {
                        url: this.programForm.programUrl
                    }
                }).then(res => {
                    if (res.code === 200) {
                        this.programForm = { 
                            programId: '', 
                            programTypeId: [], 
                            programName: '', 
                            performers: '', 
                            description: '', 
                            orderNo: '', 
                            programUrl: '',
                            token: localStorage.getItem('token'),
                            showId: '',
                        };
                    }
                });
            }
            this.dialogVisible = false; // 关闭对话框
        },
        // 上移或下移节目顺序
        moveProgram(program, index, direction) {
            const targetIndex = direction === 'up' ? index - 1 : index + 1;
            if (targetIndex < 0 || targetIndex >= this.programList.length) return;
            
            const currentProgram = { ...this.programList[index] };
            const targetProgram = { ...this.programList[targetIndex] };
            
            // 检查是否属于同一个演出
            if (currentProgram.showId !== targetProgram.showId) {
                this.$message.warning('只能调整同一演出内的节目顺序');
                return;
            }
            
            // 交换顺序值
            const tempOrderNo = currentProgram.orderNo;
            currentProgram.orderNo = targetProgram.orderNo;
            targetProgram.orderNo = tempOrderNo;

            const currentParams = {
                orderNo: currentProgram.orderNo,
                token: localStorage.getItem('token'),
                programId: currentProgram.programId
            }
            const targetParams = {
                orderNo: targetProgram.orderNo,
                token: localStorage.getItem('token'),
                programId: targetProgram.programId
            }
            // 确保programTypeId是字符串
            if (Array.isArray(currentProgram.programTypeId)) {
                currentProgram.programTypeId = currentProgram.programTypeId.join(',');
            }
            if (Array.isArray(targetProgram.programTypeId)) {
                targetProgram.programTypeId = targetProgram.programTypeId.join(',');
            }
            
            // 更新两个节目的顺序
            const updatePromises = [
                service.put('/api/content/program/updateProgramOrder', currentParams),
                service.put('/api/content/program/updateProgramOrder', targetParams)
            ];

            Promise.all(updatePromises).then(responses => {
                const allSuccess = responses.every(res => res.code === 200);
                if (allSuccess) {
                    this.$message.success('调整顺序成功');
                    this.fetchProgramList();
                } else {
                    this.$message.error('调整顺序失败');
                }
            }).catch(err => {
                this.$message.error(err.message);
            });
        },
        // 自动重新排序所有节目
        reorderPrograms() {
            if (!this.selectedShowId || this.programList.length <= 1) {
                return;
            }
            
            this.$confirm('确认重新排序当前演出的节目? 将按照当前列表顺序重新分配序号（10, 20, 30...）', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 深拷贝节目列表，避免直接修改数据
                const sortedPrograms = JSON.parse(JSON.stringify(this.programList));
                
                // 重新分配顺序号
                sortedPrograms.forEach((program, index) => {
                    program.orderNo = (index + 1) * 10;
                    program.token = localStorage.getItem('token');
                    
                    // 确保programTypeId是字符串
                    if (Array.isArray(program.programTypeId)) {
                        program.programTypeId = program.programTypeId.join(',');
                    }
                });
                
                // 批量更新
                const updatePromises = sortedPrograms.map(program => 
                    service.put(`/api/content/program/updateProgramOrder/${program.programId}`, program)
                );
                
                Promise.all(updatePromises).then(responses => {
                    const allSuccess = responses.every(res => res.code === 200);
                    if (allSuccess) {
                        this.$message.success('重新排序成功');
                        this.fetchProgramList();
                    } else {
                        this.$message.error('部分节目排序失败');
                    }
                }).catch(err => {
                    this.$message.error('排序过程中发生错误: ' + err.message);
                });
            }).catch(() => {
                this.$message.info('已取消重新排序');
            });
        },
        // 表演者输入相关方法
        showInput() {
            this.inputPerformerVisible = true;
            this.$nextTick(() => {
                this.$refs.savePerformerInput.$refs.input.focus();
            });
        },
        handleInputConfirm() {
            let inputValue = this.inputPerformerValue.trim();
            if (inputValue && this.performerTags.indexOf(inputValue) === -1) {
                this.performerTags.push(inputValue);
            }
            this.inputPerformerVisible = false;
            this.inputPerformerValue = '';
        },
        handleRemovePerformer(performer) {
            this.performerTags.splice(this.performerTags.indexOf(performer), 1);
        },
        getProgramTypeName(typeId) {
            const programType = this.programTypeList.find(item => item.programTypeId === typeId);
            return programType ? programType.programTypeName : '未知类型';
        },
        getTypeNames(typeIds) {
            const typeNames = typeIds.split(',').map(id => this.getProgramTypeName(id));
            return typeNames.join(', ');
        },
        handleShowChange() {
            this.fetchProgramList();
        },
    }
};
</script>

<style scoped>
.program-list-container {
    padding: 20px;
}

.action-bar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
}

.action-left {
    display: flex;
    align-items: center;
}

.search-input {
    width: 300px;
}

.table-card {
    margin-bottom: 20px;
}

.table-toolbar {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
}

.info-text {
    margin-left: 15px;
    font-size: 12px;
    color: #909399;
}

.form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
    line-height: 1.2;
}

.program-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
    display: block;
}

.program-uploader:hover {
    border-color: #409EFF;
}

.program-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.program-image {
    width: 178px;
    height: 178px;
    display: block;
}

.performers-tags {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}

.performer-tag {
    margin: 2px;
}

.empty-data {
    padding: 40px 0;
    text-align: center;
}

.empty-data i {
    font-size: 50px;
    color: #909399;
    margin-bottom: 10px;
}

.empty-data p {
    color: #909399;
    font-size: 14px;
    margin: 0;
}

.performer-input {
    display: flex;
    flex-wrap: wrap;
}

.input-new-performer {
    width: 150px;
    margin-right: 10px;
    vertical-align: bottom;
}

.button-new-performer {
    margin-bottom: 5px;
}

.type-tags {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}

.type-tag {
    margin: 2px;
}

.empty-show-card {
    margin-top: 20px;
    padding: 60px;
    text-align: center;
}

.empty-show-message {
    color: #909399;
    font-size: 14px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.empty-show-message i {
    font-size: 60px;
    margin-bottom: 20px;
    color: #dcdfe6;
}

.empty-show-message p {
    font-size: 16px;
    margin: 0;
}
</style>